#!/usr/bin/env bash
# Replace var script that seds and greps

# Set script_dir
script_dir="$(dirname "$(realpath "$0")")"

# Source util function
source "${script_dir}/_util"

ran_col_str "Sed chad replace utility"

cmd_arg_help \
	"String to find" \
	"String to change to" \
	"File path"

# Replace text and show interactive
[[ $# -ne 3 ]] && error_msg "Replace chad accepts 3 arguments, not $#" 22

# Auto find delimeter for sed
delimeters=("|" "_" ";" "/" "#" " ")
for d in "${delimeters[@]}"; do
	# Check if no delimeter is not contained in the strings
	[[ "{$1}{$2}" != *"${d}"* ]] && delim="${d}"
	# If delimeter set, exit
	[[ -n "${delim}" ]] && break
done

[[ -z "${delim}" ]] && error_msg "Couldn't find a valid delimeter" 1

info_msg "Sed delimeter ${delim}"
info_msg "Will replace '${1}' with '${2}' in file ${3}"
grep_command=$(grep -n "${1}" "${3}")

info_msg "Before:\n${BLUE}${grep_command}"

sed -i "s${delim}${1}${delim}${2}${delim}g" "${3}"

grep_command=$(grep -n "${2}" "${3}")
info_msg "After:\n${BLUE}${grep_command}"
unset grep_command
